package org.kabeja.parser.dxf.filter;

import org.kabeja.parser.DXFValue;
import org.kabeja.parser.ParseException;

import java.util.*;

/**
 * @author shutao
 * @since 2022/4/25 10:57
 */
public class DXFStreamLayerFilter extends DXFStreamEntityFilter {
    public static final String PROPERTY_LAYERS_EXCLUDE = "layers.exclude";
    public static final String PROPERTY_LAYERS_INCLUDE = "layers.include";
    public static final int LAYER_NAME = 8;
    protected List parseValues = new ArrayList();
    protected Set exclude = new HashSet();
    protected Set include = new HashSet();
    protected String layer = "";
    boolean findLayer = true;

    public DXFStreamLayerFilter() {
    }

    @Override
    public void setProperties(Map var1) {
        StringTokenizer var2;
        if (var1.containsKey("layers.include")) {
            this.include.clear();
            var2 = new StringTokenizer((String)var1.get("layers.include"), "|");

            while(var2.hasMoreTokens()) {
                String var3 = var2.nextToken();
                this.include.add(var3);
            }
        }

        if (var1.containsKey("layers.exclude")) {
            this.exclude.clear();
            var2 = new StringTokenizer((String)var1.get("layers.exclude"), "|");

            while(var2.hasMoreTokens()) {
                this.exclude.add(var2.nextToken());
            }
        }

    }

    @Override
    protected void endEntity() throws ParseException {
        if (this.include.contains(this.layer)) {
            this.outputEntity();
        } else if (!this.exclude.contains(this.layer)) {
            this.outputEntity();
        }

    }

    protected void outputEntity() throws ParseException {
        for(int var1 = 0; var1 < this.parseValues.size(); ++var1) {
            DXFStreamLayerFilter.ParseValue var2 = (DXFStreamLayerFilter.ParseValue)this.parseValues.get(var1);
            this.handler.parseGroup(var2.getGroupCode(), var2.getDXFValue());
        }

    }

    @Override
    protected void startEntity(String var1) throws ParseException {
        this.parseValues.clear();
        this.findLayer = true;
    }

    @Override
    protected void parseEntity(int var1, DXFValue var2) throws ParseException {
        if (this.findLayer && var1 == 8) {
            this.layer = var2.getValue();
            this.findLayer = false;
        }

        DXFStreamLayerFilter.ParseValue var3 = new DXFStreamLayerFilter.ParseValue(var1, var2);
        this.parseValues.add(var3);
    }

    private class ParseValue {
        int groupCode;
        DXFValue value;

        public ParseValue(int var2, DXFValue var3) {
            this.groupCode = var2;
            this.value = var3;
        }

        public int getGroupCode() {
            return this.groupCode;
        }

        public DXFValue getDXFValue() {
            return this.value;
        }
    }
}
